package com.htfyun.roobofactory.rooboUtils;

import android.media.AudioRecord;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by yuanshuqi on 2016/5/13 17:21.
 * email:yuanshuqi@roo.bo
 */
public class RooboRecorder {
    private static final String TAG = "RooboRecorder";
    private final RooboEngine engine;
    private AudioRecord mAudioRecord;
    private int mRecBufSize;
    private byte[] mDataBuffer;
    private int count;
    private boolean mDestroy = false;
    private ExecutorService mReadExecutor;
    private Runnable mReadTask;
    private boolean mHasStart;
    private File mAudioFile  = null;

    public RooboRecorder(RooboEngine engine) {
        mRecBufSize = AudioRecord.getMinBufferSize(AudioFileAttribute.AUDIO_SAMPLE_RATE,
                AudioFileAttribute.CHANNEL_CONFIGURATION, AudioFileAttribute.ENCODING_BIT_RATE);
        mReadTask = new ReadRunnable();
        mDataBuffer = new byte[mRecBufSize];
        this.engine = engine;
        File fpath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data/wakeup/");
        Log.d(TAG,Environment.getExternalStorageDirectory().getAbsolutePath());
        deleteFolderFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data/wakeup/",true);
        fpath.mkdirs();//创建文件夹

        try {
            //创建临时文件,注意这里的格式为.pcm
            mAudioFile = File.createTempFile("wakeup", ".pcm", fpath);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {// 处理目录
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {// 如果是文件，删除
                        file.delete();
                    } else {// 目录
                        if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private DataOutputStream mdos = null;

    private class ReadRunnable implements Runnable {

        @Override
        public void run() {

            try{
                mdos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(mAudioFile)));
            }catch(Exception e){

            }
            mAudioRecord.startRecording();
            Log.e(TAG, "RooboRecorder begin recording... mDestroy = " + mDestroy + ",mAudioRecord = " + mAudioRecord);
            while (!mDestroy) {
                int len = 0;
                if (mAudioRecord != null) {
                    try {
                        len = mAudioRecord.read(mDataBuffer, 0, mRecBufSize);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }

                /*try{
                    Log.d(TAG,"len :" + len);
                    mdos.write(mDataBuffer,0,len);
                }catch (IOException e){

                }*/

                byte[] data = new byte[len];
                System.arraycopy(mDataBuffer, 0, data, 0, len);
                engine.produceData(data);
            }
        }
    }

    public void startRecord() {
        if (mHasStart) {
            Log.e(TAG, "has start record ,return");
            return;
        }
        mHasStart = true;
        mAudioRecord = new AudioRecord(AudioFileAttribute.AUDIO_INPUT,
                AudioFileAttribute.AUDIO_SAMPLE_RATE, AudioFileAttribute.CHANNEL_CONFIGURATION,
                AudioFileAttribute.ENCODING_BIT_RATE, mRecBufSize * 2);
        mReadExecutor = Executors.newSingleThreadExecutor();
        mDestroy = false;
        mReadExecutor.submit(mReadTask);
    }

    public void pauseRecord() {
        destroyRecorder();
    }

    public void resumeRecord() {
        startRecord();
    }

    public void destroyRecorder() {
        Log.d(TAG, "1648k 16K destroyRecorder called");
        mHasStart = false;
        mDestroy = true;
        if (mAudioRecord != null) {
            mAudioRecord.stop();
            mAudioRecord.release();
            mAudioRecord = null;
        }
        if (mReadExecutor != null) {
            mReadExecutor.shutdownNow();
            mReadExecutor = null;
        }
        deleteFolderFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data/wakeup/",true);
        Log.d(TAG, "AudioRecord destroy finish,buffSize = " + mRecBufSize);
    }
}
